package com.netty.pro.netty.nio.GroupChat;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * @author xuzn
 * @ClassName: GroupClient
 * @ProjectName echo-project
 * @date 2020/3/8/19:33
 */
public class GroupClient {
  private final String HOST = "127.0.0.1";
  private final int PORT = 6666;
  private Selector selector;
  private SocketChannel socketChannel;
  private String username;

  public GroupClient() throws Exception {
    selector = Selector.open();
    socketChannel = SocketChannel.open();
    socketChannel.socket().connect(new InetSocketAddress(HOST, PORT));
    socketChannel.configureBlocking(false);
    socketChannel.register(selector, SelectionKey.OP_READ);
    // 拿到地址
    username = socketChannel.getLocalAddress().toString().substring(1);
    System.out.println(username + "is ok");
  }

  // 发送消息
  public void sendMsg(String info) throws Exception {
    info = username + "说" + info;
    ByteBuffer byteBuffer = ByteBuffer.wrap(info.getBytes());
    socketChannel.write(byteBuffer);
  }

  // 从服务器端读取消息
  public void readInfo() {
    try {
      // 有事件发生的channel个数
      int readChannels = selector.select();
      if (readChannels > 0) {
        // 得到相应的key集合
        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while (iterator.hasNext()) {
          SelectionKey key = iterator.next();
          if (key.isReadable()) {
            // 得到相应的channel
            SocketChannel sc = (SocketChannel) key.channel();
            // 创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            sc.read(buffer);
            System.out.println(new String(buffer.array()));
          }
        }
      } else {
        System.out.println("没有可用的通道");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) throws Exception {
    GroupClient groupClient = new GroupClient();

    // 读取从服务器端发送的数据
    new Thread() {
      @Override
      public void run() {
        while (true) {
          groupClient.readInfo();
          try {
            Thread.currentThread().sleep(3000);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    }.start();

    // 发送数据给服务端
    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextLine()) {
      String line = scanner.nextLine();
      groupClient.sendMsg(line);
    }
  }
}
